package com.xpalive.config.spring.Respbody;

import com.xpalive.base.dto.result.RespResult;
import com.xpalive.config.spring.Respbody.RespResultWrap;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * control 增强器 用于处理全局异常
 */
@RestControllerAdvice
@Slf4j
public class ControllerRespAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter,
        Class<? extends HttpMessageConverter<?>> aClass) {
        final Method method = methodParameter.getMethod();
        final Class<?> declaringClass = method.getDeclaringClass();
        RespResultWrap annotation;
        if (method.isAnnotationPresent(RespResultWrap.class)) {
            annotation = method.getAnnotation(RespResultWrap.class);
            return annotation.active();
        } else {
            if (declaringClass.isAnnotationPresent(RespResultWrap.class)) {
                annotation = declaringClass.getAnnotation(RespResultWrap.class);
                return annotation.active();
            } else {
                return false;
            }
        }
    }

    @Override
    public Object beforeBodyWrite(Object obj, MethodParameter methodParameter, MediaType mediaType,
        Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
        ServerHttpResponse serverHttpResponse) {
        if (obj instanceof RespResult) {
            return obj;
        } else {
            return RespResult.ofSuccess(obj);
        }
    }
}
